package cn.fintecher.pangolin.service.manage.web;

import cn.fintecher.pangolin.common.model.UserModel;
import cn.fintecher.pangolin.common.response.LoginResponse;
import cn.fintecher.pangolin.common.web.BaseController;
import cn.fintecher.pangolin.entity.mysql.User;
import cn.fintecher.pangolin.service.manage.repository.UserRepository;
import cn.fintecher.pangolin.service.manage.request.*;
import cn.fintecher.pangolin.service.manage.response.SimpleUserResponse;
import cn.fintecher.pangolin.service.manage.response.UserDetailResponse;
import cn.fintecher.pangolin.service.manage.response.UserResponse;
import cn.fintecher.pangolin.service.manage.service.BaseService;
import cn.fintecher.pangolin.service.manage.service.UserService;
import com.querydsl.core.BooleanBuilder;
import io.swagger.annotations.*;
import org.apache.commons.collections4.IterableUtils;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * @Auther: xiaqun
 * @Description: 用户相关接口
 * @Date: 14:45 2019/8/13
 */

@RestController
@RequestMapping("/api/userController")
@Api(value = "用户相关接口", description = "用户相关接口")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private BaseService baseService;

    /**
     * 用户登录
     */
    @ApiOperation(value = "用户登录", notes = "用户登录")
    @PostMapping("/login")
    public ResponseEntity<LoginResponse> login(HttpServletRequest request,
                                               @Valid @RequestBody LoginRequest loginRequest) {
        log.info("REST request to login,{}", loginRequest);
        LoginResponse response = userService.login(request, loginRequest);
        return ResponseEntity.ok().body(response);
    }

    /**
     * APP用户登录
     */
    @ApiOperation(value = "APP用户登录", notes = "APP用户登录")
    @PostMapping("/appLogin")
    public ResponseEntity<LoginResponse> appLogin(HttpServletRequest request,
                                                  @Valid @RequestBody LoginRequest loginRequest) {
        log.info("REST request to app login,{}", loginRequest);
        LoginResponse response = userService.appLogin(request, loginRequest);
        return ResponseEntity.ok().body(response);
    }

    /**
     * 用户登出
     */
    @ApiOperation(value = "用户登出", notes = "用户登出")
    @GetMapping("/logout")
    public ResponseEntity<Void> logout(@RequestHeader(value = "X-UserToken") String token) {
        log.info("REST request to logout");
        userService.logout(token);
        return ResponseEntity.ok().build();
    }

    /**
     * 通过token获取用户
     */
    @ApiOperation(value = "通过token获取用户", notes = "通过token获取用户")
    @GetMapping("/getUserByToken/{token}")
    public ResponseEntity<LoginResponse> getUserByToken(@PathVariable(value = "token") String token) {
        LoginResponse loginResponse = userService.getUserByToken(token);
        return Optional.ofNullable(loginResponse)
                .map(result -> new ResponseEntity<>(
                        result,
                        HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.FORBIDDEN));
    }

    /**
     * 删除用户
     */
    @ApiOperation(value = "通过id删除用户", notes = "通过id删除用户")
    @DeleteMapping("/deleteUserById")
    public ResponseEntity deleteUserById(@RequestHeader(value = "X-UserToken") String token, @RequestParam(value = "userId") String userId) {
        LoginResponse loginResponse = userService.getUserByToken(token);
        userService.deleteUser(userId, loginResponse);
        return ResponseEntity.ok().build();
    }

    /**
     * 新增用户
     */
    @ApiOperation(value = "新增用户", notes = "新增用户")
    @PostMapping("/addUser")
    public ResponseEntity<Void> addUser(@Valid @RequestBody AddUserRequest request,
                                        @RequestHeader(value = "X-UserToken") String token) {
        log.info("REST request to add user,{}", request);
        userService.addUser(request, token);
        return ResponseEntity.ok().build();
    }

    /**
     * 修改用户
     */
    @ApiOperation(value = "修改用户", notes = "修改用户")
    @PutMapping("/modifyUser")
    public ResponseEntity<Void> modifyUser(@Valid @RequestBody ModifyUserRequest request,
                                           @RequestHeader(value = "X-UserToken") String token) {
        log.info("REST request to modify user,{}", request);
        userService.modifyUser(request, token);
        return ResponseEntity.ok().build();
    }

    /**
     * 重置/修改密码
     */
    @ApiOperation(value = "重置/修改密码", notes = "重置/修改密码")
    @PutMapping("/resetPassword")
    public ResponseEntity<Void> resetPassword(@Valid @RequestBody ResetPasswordRequest request,
                                              @RequestHeader(value = "X-UserToken") String token) {
        log.info("REST request to reset password,{}", request);
        userService.resetPassword(request, token);
        return ResponseEntity.ok().build();
    }

    /**
     * @Author wangxiangdong
     * @Description 更新密码
     * @Date 2019/10/28 10:56
     **/
    @ApiOperation(value = "更新密码", notes = "更新密码")
    @PostMapping("/updatePassword")
    public ResponseEntity<Void> updatePassword(@RequestBody UpdatePasswordRequest request, @RequestHeader(value = "X-UserToken") String token) {
        UserModel userModel = baseService.getUserByToken(token);
        userService.updatePassword(request, userModel);
        return ResponseEntity.ok().build();
    }

    /**
     * 多条件查询用户
     */
    @ApiOperation(value = "多条件查询用户", notes = "多条件查询用户")
    @GetMapping("/findUserByDepartment")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", dataType = "int", paramType = "query",
                    value = "页数 (0..N)"),
            @ApiImplicitParam(name = "size", dataType = "int", paramType = "query",
                    value = "每页大小."),
            @ApiImplicitParam(name = "sort", allowMultiple = true, dataType = "string", paramType = "query",
                    value = "依据什么排序: 属性名(,asc|desc). ")
    })
    public ResponseEntity<Page<UserResponse>> findUserByDepartment(FindUserRequest request, Pageable pageable) {
        log.info("REST request to find user by department,{}", request);
        Page<UserResponse> page = userService.findUserByDepartment(request, pageable);
        return ResponseEntity.ok().body(page);
    }


    @ApiOperation(value = "根据部门code查询用户", notes = "根据部门code查询用户")
    @GetMapping("/findUserByDepartmentCode")
    public ResponseEntity<List<UserResponse>> findUserByDepartmentCode(UserRequest userRequest) {
        BooleanBuilder booleanBuilder = userRequest.getBuilder();
        Iterable<User> iterable = userRepository.findAll(booleanBuilder);
        List<User> list = IterableUtils.toList(iterable);
        Type listType = new TypeToken<List<UserResponse>>() {
        }.getType();
        List<UserResponse> responses = modelMapper.map(list, listType);
        return ResponseEntity.ok().body(responses);
    }

    /**
     * 查询用户详情
     */
    @ApiOperation(value = "查询用户详情", notes = "查询用户详情")
    @GetMapping("/getUserDetail")
    public ResponseEntity<UserDetailResponse> getUserDetail(@RequestParam @ApiParam(value = "用户ID", required = true) String userId) {
        log.info("REST request to get user detail,{}", userId);
        UserDetailResponse response = userService.getUserDetail(userId);
        return ResponseEntity.ok().body(response);
    }

    /**
     * 查询用户所分配角色
     */
    @ApiOperation(value = "查询用户所分配角色", notes = "查询用户所分配角色")
    @GetMapping("/getRoles")
    public ResponseEntity<Set<String>> getRoles(@RequestParam @ApiParam(value = "用户ID", required = true) String userId) {
        log.info("REST request to get roles,{}", userId);
        Set<String> set = userService.getRoles(userId);
        return ResponseEntity.ok().body(set);
    }

    /**
     * 用户解锁
     */
    @ApiOperation(value = "用户解锁", notes = "用户解锁")
    @GetMapping("/unlock")
    public ResponseEntity<Void> unlock(@RequestParam @ApiParam(value = "用户ID", required = true) String userId,
                                       @RequestHeader(value = "X-UserToken") String token) {
        log.info("REST request to unlock,{}", userId);
        userService.unlock(userId, token);
        return ResponseEntity.ok().build();
    }

    /**
     * 一键解锁
     */
    @ApiOperation(value = "一键解锁", notes = "一键解锁")
    @GetMapping("/batchUnlock")
    public ResponseEntity<Void> batchUnlock(@RequestHeader(value = "X-UserToken") String token) {
        log.info("REST request to batch unlock");
        userService.batchUnlock(token);
        return ResponseEntity.ok().build();
    }

    /**
     * 通过Id获取用户职位状态
     */
    @ApiOperation(value = "通过Id获取用户职位状态", notes = "通过Id获取用户职位状态")
    @GetMapping("/getUserStateById")
    public ResponseEntity<String> getUserStateById(@RequestParam("userId") String userId) {
        User user = userRepository.getOne(userId);
        return ResponseEntity.ok().body(user.getStatus().name());
    }

    /**
     * 获取部门下用户
     */
    @ApiOperation(value = "获取部门下用户", notes = "获取部门下用户")
    @GetMapping("/getSimpleUser")
    public ResponseEntity<List<SimpleUserResponse>> getSimpleUser(@RequestParam @ApiParam(value = "部门code", required = true) String departCode) {
        log.info("REST request to get simple user,{}", departCode);
        List<SimpleUserResponse> list = userService.getSimpleUser(departCode);
        return ResponseEntity.ok().body(list);
    }
}
